package com.yys.gulimall.ware.listener;

import com.rabbitmq.client.Channel;
import com.yys.common.to.mq.OrderTo;
import com.yys.common.to.mq.StockLockTo;
import com.yys.gulimall.ware.constant.WareConstant;
import com.yys.gulimall.ware.service.WareSkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author zq
 * @version 1.0
 * @date 2021/4/6 14:00
 */
@Service
@Slf4j
@RabbitListener(queues = WareConstant.STOCK_RELEASE_QUEUE)
public class StockReleaseListener {

    @Autowired
    private WareSkuService wareSkuService;

    @RabbitHandler
    public void handlerStockLockedRelease(StockLockTo stockLockTo, Message message , Channel channel) throws IOException {

        log.info("收到库存解锁消息... {}" + stockLockTo);
        // 我们可以结合redelivered和redis记录消息唯一id来保证接口幂等
//        Boolean redelivered = message.getMessageProperties().getRedelivered();
        try {
            wareSkuService.unlockStock(stockLockTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    @RabbitHandler
    public void handleOrderCloseStockLockRelease(OrderTo orderTo,Message message,Channel channel) throws IOException {
        log.info("收到订单关闭主动解锁库存消息... {}" + orderTo);
        try {
            wareSkuService.unlockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }



}
